package com.ymttest.business.service.shenqi;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Random;

import org.apache.http.client.ClientProtocolException;
import org.json.JSONArray;
import org.json.JSONObject;

import com.google.gson.JsonObject;
import com.shop2cn.iapi.activitymgt.parameter.AddactivityBean;
import com.shop2cn.iapi.activitymgt.parameter.CatalogAgentBean;
import com.shop2cn.iapi.activitymgt.parameter.ProductAgentBean;
import com.shop2cn.iapi.shenqisettlement.parameter.bean.AgentProductBean;
import com.shop2cn.iapi.agentproducts.parameter.AddAgentProductBean;
import com.shop2cn.iapi.agentproducts.parameter.CatalogPriceDto;
import com.shop2cn.iapi.agentproducts.parameter.GetPriceByCatalogIdListBean;
import com.shop2cn.iapi.agentproducts.parameter.ProductDetailsBean;
import com.shop2cn.iapi.agentproducts.parameter.ProductDetailsDto;
import com.shop2cn.iapi.agentproducts.parameter.SubCatalogDto;
import com.shop2cn.iapi.agentproducts.service.AddAgentProductCall;
import com.shop2cn.iapi.agentproducts.service.GetPriceByCatalogIdListCall;
import com.shop2cn.iapi.agentproducts.service.ProductDetailsCall;
import com.ymt.base.YmatouEasyCall;
import com.ymt.core.tool.FormatUtil;
import com.ymt.core.tool.Logger;
import com.ymttest.business.service.AddAgentProductCallService;
import com.ymttest.business.service.AgentProductCallServiceV2;
import com.ymttest.business.service.shenqi.bean.PackageInfoByCatalogIdListResponse;
import com.ymttest.database.sharding.db.sharding.model.ShenqiProxyChainPo;

public class SqTradingProductService {
	
	/**
	 * 获取商品详情
	 * @param userId
	 * @param productId
	 * @return
	 * @throws ClientProtocolException
	 * @throws IOException
	 */
	public static ProductDetailsDto getProductDetails(Long userId,
			String productId) throws ClientProtocolException, IOException {

		ProductDetailsBean productDetailsBean = new ProductDetailsBean();
		ProductDetailsCall productdetailsCall = new ProductDetailsCall();

		productDetailsBean.setProductId(productId);
		productDetailsBean.setUserId(userId.intValue());

		productdetailsCall.setData(productDetailsBean);
		productdetailsCall.callService();

		String product = productdetailsCall.getJsonObject().get("data")
				.toString();

		ProductDetailsDto productDetailsDto = (ProductDetailsDto) FormatUtil
				.GSONToObject(product, ProductDetailsDto.class);

		return productDetailsDto;
	}
	
	public static PackageInfoByCatalogIdListResponse getPackageInfoByCatalogIdList(Long goodsOwnerId, List<String> catalogIds)
			throws Exception {

		JsonObject jsonObject = AddAgentProductCallService
				.GetPackageInfoByCatalogIdList(goodsOwnerId.intValue(), catalogIds);

		PackageInfoByCatalogIdListResponse resp = (PackageInfoByCatalogIdListResponse) FormatUtil
				.GSONToObject(jsonObject.getAsJsonObject("data").toString(),
						PackageInfoByCatalogIdListResponse.class);

		return resp;
	}
	
	/**
	 * 添加组合商品
	 * @param sellerId
	 * @param currency
	 * @param isMultiCode
	 * @return
	 * @throws Exception
	 */
	public static String AddComposeAgentProduct(int sellerId, String currency, Boolean isMultiCode) throws Exception {
    	
    	AddAgentProductCall addagentproductCall = new AddAgentProductCall();
    	
    	AddAgentProductBean Product1 = null;
    	
    	if (isMultiCode)
    		Product1 = AddAgentProductCallService
					.initAddMultiCodeAgentProduct(sellerId, "", false);
		else
			Product1 = AddAgentProductCallService
					.initAddAgentProduct(sellerId, "", true);
    	
    	Product1.setCurrency(currency);
		Product1.getCatalogList().remove(0);
		Product1.setBrandId(10105);
		
		AddAgentProductCallService.AddAgentProduct(Product1);
		
		AddAgentProductBean Product2 = null;
		
		if (isMultiCode)
			Product2 = AddAgentProductCallService
					.initAddMultiCodeAgentProduct(sellerId, "", false);
		else
			Product2 = AddAgentProductCallService
					.initAddAgentProduct(sellerId, "", true);
		
		Product2.setCurrency(currency);
		Product2.getCatalogList().remove(0);
		Product2.setBrandId(22125);
		
		AddAgentProductCallService.AddAgentProduct(Product2);
		
		// 创建组合商品主商品
		AddAgentProductBean addAgentProductBean = null;
		
		addAgentProductBean = AddAgentProductCallService
				.initAddAgentProduct(sellerId, "", true);
		
		addAgentProductBean.getCatalogList().remove(1);
		SubCatalogDto subCatalogDto = new SubCatalogDto();
		subCatalogDto.setSkuId(Product1.getCatalogList().get(0).getSku());
		subCatalogDto.setBarcode(Product1.getCatalogList().get(0).getBarcode());
		subCatalogDto.setSalePrice(new BigDecimal(620).doubleValue());
		subCatalogDto.setNum(2);
		
		SubCatalogDto subCatalogDto1 = new SubCatalogDto();
		subCatalogDto1.setSkuId(Product2.getCatalogList().get(0).getSku());
		subCatalogDto1.setBarcode(Product2.getCatalogList().get(0).getBarcode());
		subCatalogDto1.setSalePrice(new BigDecimal(310).doubleValue());
		subCatalogDto1.setNum(1);
		
		addAgentProductBean.setCurrency(currency);
		addAgentProductBean.setBrandId(11091);
		addAgentProductBean.setSubCatalogs(Arrays.asList(subCatalogDto,subCatalogDto1));
		
		addAgentProductBean.getCatalogList().forEach(catalogDto -> {
			
			catalogDto.setStock(5);
		});
		
		addagentproductCall.setData(addAgentProductBean);
		addagentproductCall.callService();
		Logger.verifyEquals("200", addagentproductCall.getString("code"), "验证Code");
    	
		String productId = addagentproductCall.getJsonObject().get("data").getAsJsonObject().get("newProductId")
				.getAsString();

		return productId;
    }
	
	public static CatalogPriceDto getPriceByCatalogIdList(
			List<String> catalogIdList, Long userId)
			throws ClientProtocolException, IOException {

		GetPriceByCatalogIdListBean getpricebycatalogidlistBean = new GetPriceByCatalogIdListBean();
		GetPriceByCatalogIdListCall getpricebycatalogidlistCall = new GetPriceByCatalogIdListCall();

		getpricebycatalogidlistBean.setCatalogIdList(catalogIdList);
		getpricebycatalogidlistBean.setUserId(userId.intValue());

		getpricebycatalogidlistCall.setData(getpricebycatalogidlistBean);
		getpricebycatalogidlistCall.callService();

		return getpricebycatalogidlistCall.getCatalogPriceList().get(0);
	}
	
	/**
	 * 根據catalogId 获取关系链
	 * 
	 * @param catalogId
	 * @return
	 */
	public static List<ShenqiProxyChainPo> getProxyChainInfoList(String catalogId, long sellerId) {

		List<ShenqiProxyChainPo> shenqiProxyChainPoList = new ArrayList<ShenqiProxyChainPo>();

		YmatouEasyCall queryAgentPriceChainCall = new YmatouEasyCall("",
				"POST", "JSON");
		String orderJson = "{\"catalogIds\":[\"" + catalogId
				+ "\"], \"userId\":" + sellerId + "}";
		queryAgentPriceChainCall
				.setUrl("http://agentproducts.iapi.shop2cn.com/product/queryAgentPriceChain");
		queryAgentPriceChainCall.setData(orderJson);

		try {
			queryAgentPriceChainCall.callService();

			JSONObject data = new JSONObject(
					queryAgentPriceChainCall.getReturnData())
					.optJSONObject("data");

			if (null == data)
				return null;
			else {

				Logger.debug("returndata:"
						+ data.optJSONObject("catalogPriceLinkMap")
								.optJSONArray(catalogId));
				JSONArray proxyChain = data
						.optJSONObject("catalogPriceLinkMap").optJSONArray(
								catalogId);
				
				BigDecimal costPrice = new BigDecimal(data.optJSONObject(
						"costPriceMap").optDouble(catalogId)).setScale(2);

				for (int i = 0; i < proxyChain.length(); i++) {

					JSONObject object = new JSONObject(proxyChain.get(i)
							.toString());
					ShenqiProxyChainPo po = new ShenqiProxyChainPo();

					po.setTitle(object.optString("title"));
					po.setPictureUrl(object.optString("pictureUrl"));
					po.setFromParentPrice(new BigDecimal(object
							.optDouble("fromParentPrice")).setScale(2));
					po.setToChildPrice(new BigDecimal(object
							.optDouble("toChildPrice")).setScale(2));
					po.setIndexInChain(i);
					po.setSellerId(object.optLong("sellerId"));
					po.setCatalogId(catalogId);
					po.setProxyCatalogId(object.optString("catalogId"));
					po.setFromParentPriceType(object
							.optInt("fromParentPriceType"));

					po.setSalePrice(Double.isNaN(object.optDouble("salePrice")) ? null
							: new BigDecimal(object.optDouble("salePrice")));

					if (i == proxyChain.length() - 1) {
						po.setChildSellerId(0L);
					} else {
						po.setChildSellerId(new JSONObject(proxyChain
								.get(i + 1).toString()).optLong("sellerId"));
					}

					String currency = data.getString("currency");
					po.setCurrency(currency);
					po.setCostPrice(costPrice);

					shenqiProxyChainPoList.add(po);
				}
			}

			Logger.debug("ShenqiProxyChainPoList:" + shenqiProxyChainPoList);

		} catch (Exception e) {

			e.printStackTrace();
		}

		return shenqiProxyChainPoList;
	}
	
	/**
	 * 根據catalogId 获取关系链 分销小店
	 * 
	 * @param catalogId
	 * @return
	 */
	public static List<ShenqiProxyChainPo> getInheritedProxyChainInfo(
			String catalogId, long sellerId) {

		List<ShenqiProxyChainPo> shenqiProxyChainPoList = new ArrayList<ShenqiProxyChainPo>();

		YmatouEasyCall queryAgentPriceChainCall = new YmatouEasyCall("",
				"POST", "JSON");
		String orderJson = "{\"catalogIds\":[\"" + catalogId
				+ "\"], \"userId\":" + sellerId + "}";
		queryAgentPriceChainCall
				.setUrl("http://agentproducts.iapi.shop2cn.com/product/queryAgentPriceChain");
		queryAgentPriceChainCall.setData(orderJson);

		try {
			queryAgentPriceChainCall.callService();

			JSONObject data = new JSONObject(
					queryAgentPriceChainCall.getReturnData())
					.optJSONObject("data");

			if (null == data)
				return null;
			else {

				Logger.debug("returndata:"
						+ data.optJSONObject("catalogPriceLinkMap")
								.optJSONArray(catalogId));
				JSONArray proxyChain = data
						.optJSONObject("catalogPriceLinkMap").optJSONArray(
								catalogId);
				BigDecimal costPrice = new BigDecimal(data.optJSONObject(
						"costPriceMap").optDouble(catalogId)).setScale(2);

				for (int i = 0; i < proxyChain.length(); i++) {

					JSONObject object = new JSONObject(proxyChain.get(i)
							.toString());
					ShenqiProxyChainPo po = new ShenqiProxyChainPo();

					po.setTitle(object.optString("title"));
					po.setPictureUrl(object.optString("pictureUrl"));
					po.setFromParentPrice(new BigDecimal(object
							.optDouble("fromParentPrice")).setScale(2));
					po.setToChildPrice(new BigDecimal(object
							.optDouble("toChildPrice")).setScale(2));
					po.setIndexInChain(i);
					po.setSellerId(object.optLong("sellerId"));
					po.setCatalogId(catalogId);
					po.setProxyCatalogId(object.optString("catalogId"));
					po.setFromParentPriceType(object
							.optInt("fromParentPriceType"));
					po.setSalePrice(new BigDecimal(object
							.optString("salePrice")));

					if (i == proxyChain.length() - 1) {
						po.setChildSellerId(0L);
						po.setIsFenxiaoShop(true);
					} else {
						po.setChildSellerId(new JSONObject(proxyChain
								.get(i + 1).toString()).optLong("sellerId"));
					}

					String currency = data.getString("currency");
					po.setCurrency(currency);
					
					po.setCostPrice(costPrice);

					shenqiProxyChainPoList.add(po);
				}
			}

			Logger.debug("ShenqiProxyChainPoList:" + shenqiProxyChainPoList);

		} catch (Exception e) {

			e.printStackTrace();
		}

		return shenqiProxyChainPoList;
	}
	
	/**
	 * 根據catalogId, sellerid 获取sellerid对应的规格价格
	 * 
	 * @param catalogId
	 * @param sellerId
	 * @return
	 */
	public static ShenqiProxyChainPo getProxyChainInfo(String catalogId,
			long sellerId) {

		ShenqiProxyChainPo po = new ShenqiProxyChainPo();

		YmatouEasyCall queryAgentPriceChainCall = new YmatouEasyCall("",
				"POST", "JSON");
		String orderJson = "{\"catalogIds\":[\"" + catalogId
				+ "\"], \"userId\":" + sellerId + "}";
		queryAgentPriceChainCall
				.setUrl("http://agentproducts.iapi.shop2cn.com/product/queryAgentPriceChain");
		queryAgentPriceChainCall.setData(orderJson);

		try {
			queryAgentPriceChainCall.callService();

			JSONObject data = new JSONObject(
					queryAgentPriceChainCall.getReturnData())
					.optJSONObject("data");

			if (null == data)
				return null;
			else {

				Logger.debug("returndata:"
						+ data.optJSONObject("catalogPriceLinkMap")
								.optJSONArray(catalogId));
				JSONArray proxyChain = data
						.optJSONObject("catalogPriceLinkMap").optJSONArray(
								catalogId);

				for (int i = 0; i < proxyChain.length(); i++) {

					JSONObject object = new JSONObject(proxyChain.get(i)
							.toString());

					if (object.optLong("sellerId") == sellerId) {

						po = new ShenqiProxyChainPo();

						po.setTitle(object.optString("title"));
						po.setPictureUrl(object.optString("pictureUrl"));
						po.setFromParentPrice(new BigDecimal(object
								.optDouble("fromParentPrice")).setScale(2));
						po.setToChildPrice(new BigDecimal(object
								.optDouble("toChildPrice")).setScale(2));
						po.setIndexInChain(i);
						po.setSellerId(object.optLong("sellerId"));
						po.setCatalogId(catalogId);
						po.setFromParentPriceType(object
								.optInt("fromParentPriceType"));

						if (i == proxyChain.length() - 1) {
							po.setChildSellerId(0L);
						} else {
							po.setChildSellerId(new JSONObject(proxyChain.get(
									i + 1).toString()).optLong("sellerId"));
						}
					}
				}

				String currency = data.getString("currency");
				po.setCurrency(currency);
			}

			Logger.debug("shenqiProxyChainPo:" + po);

		} catch (Exception e) {

			e.printStackTrace();
		}

		return po;
	}
	
	public static Integer agentProductAddActivity(AgentProductBean productBean, Boolean useSubCode)
			throws ClientProtocolException, IOException {

		// 创建活动商品
		AddactivityBean addactivityBean = AgentProductCallServiceV2
				.initProductaddactivity((int) productBean.getSellerId(),
						productBean.getProductId(), 1, 5, useSubCode);

		addactivityBean.setDiscountType(1);
		addactivityBean
				.getProductList()
				.get(0)
				.getCatalogList()
				.stream()
				.forEach(catalog -> {
					// catalog.setDiscount(catalog);
						catalog.setDiscountPrice(new BigDecimal(new Random()
								.nextInt(20) + 800));
					});

		return AgentProductCallServiceV2
				.agentProductaddactivity(addactivityBean);
	}

	public static Integer agentProductAddPreSaleActivity(AgentProductBean productBean,
														 Boolean useSubCode,
														 int preSaleStock)
			throws ClientProtocolException, IOException {

		// 创建活动商品
		AddactivityBean addactivityBean = AgentProductCallServiceV2
				.initProductaddactivity((int) productBean.getSellerId(),
						productBean.getProductId(), 1, 5, useSubCode);

		addactivityBean.setDiscountType(1);
		addactivityBean
				.getProductList()
				.get(0)
				.getCatalogList()
				.stream()
				.forEach(catalog -> {
					// catalog.setDiscount(catalog);
					catalog.setDiscountPrice(new BigDecimal(new Random()
							.nextInt(20) + 800));
					catalog.setStockType(1);
					catalog.setPreSaleStock(preSaleStock);
				});

		return AgentProductCallServiceV2
				.agentProductaddactivity(addactivityBean);
	}
	
	public static Integer agentProductAddInnerSaleActivity(AgentProductBean productBean, Boolean useSubCode)
			throws ClientProtocolException, IOException {

		// 创建活动商品
		AddactivityBean addactivityBean = AgentProductCallServiceV2
				.initProductaddactivity((int) productBean.getSellerId(),
						productBean.getProductId(), 1, 5, useSubCode);
		
		addactivityBean.setActivityType(22);

		addactivityBean.setDiscountType(1);
		addactivityBean
				.getProductList()
				.get(0)
				.getCatalogList()
				.stream()
				.forEach(catalog -> {
					// catalog.setDiscount(catalog);
						catalog.setDiscountPrice(new BigDecimal(new Random()
								.nextInt(20) + 900));
					});

		return AgentProductCallServiceV2
				.agentProductaddactivity(addactivityBean);
	}
	
	public static Integer agentProductListAddActivity(List<AgentProductBean> productBeanList)
			throws ClientProtocolException, IOException {

		// 创建活动商品
		AddactivityBean addactivityBean = AgentProductCallServiceV2
				.initProductaddactivity((int) productBeanList.get(0).getSellerId(),
						productBeanList.get(0).getProductId());

		addactivityBean.setDiscountType(1);
		
		addactivityBean
				.getProductList()
				.get(0)
				.getCatalogList()
				.stream()
				.forEach(catalog -> {
					// catalog.setDiscount(catalog);
						catalog.setDiscountPrice(new BigDecimal(new Random()
								.nextInt(20) + 850));
					});
		
		for (int i = 1; i < productBeanList.size(); i++) {
			
			ProductAgentBean productAgentBean = new ProductAgentBean();
			AgentProductBean agentProductBean = productBeanList.get(i);
			
			productAgentBean.setProductId(agentProductBean.getProductId());
			
			List<String> catalogList = new ArrayList<String>();
			ProductDetailsDto selectProductDetails = AddAgentProductCallService
					.selectProductDetails((int) agentProductBean.getSellerId(),
							agentProductBean.getProductId());
			selectProductDetails.getCatalogList().forEach(a -> {
				catalogList.add(a.getCatalogId());
			});

			List<CatalogAgentBean> list1 = new ArrayList<CatalogAgentBean>();
			catalogList.forEach(e -> {
				CatalogAgentBean c = new CatalogAgentBean();
				c.setCatalogId(e);
				c.setDiscount(new BigDecimal("2"));// 折扣，例如：8.5折，值为：8.5
					c.setDiscountPrice(new BigDecimal(
							new Random().nextInt(20) + 850));
					c.setActivityStock(0);
					list1.add(c);
				});
			
			productAgentBean.setCatalogList(list1);
			
			addactivityBean.getProductList().add(productAgentBean);	
		}
		
		return AgentProductCallServiceV2
				.agentProductaddactivity(addactivityBean);
	}
	
	public static void main(String[] args) throws Exception {
		
//		TradingProductService.getProductDetails(500002490L, "p4820997");
//		TradingSQProductService.getPackageInfoByCatalogIdList(500002490L, Arrays.asList("c8026255"));
		SqTradingProductService.getPriceByCatalogIdList(Arrays.asList("c9296946"), 501395811L);
	}
}
